package com.itheima.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.common.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;

/**
 * @author 林晓伟
 */
@RestController
@RequestMapping("/common")
public class OssController {

    /**
     * H11-文件上传
     */
    @PostMapping("/upload")
    public R s(@RequestParam MultipartFile file) throws Exception {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tL6sGF8uPfHVdJcxXWB";
        String accessKeySecret = "OITrc3ThnRQ5K5xMQpmJ41yMpLkca1";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "lin9856";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "exampledir/";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        InputStream inputStream1 = file.getInputStream();

        String originalFilename = file.getOriginalFilename();

        long l = System.currentTimeMillis();

        assert originalFilename != null;
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newName = l + fileType;
        String s = objectName + newName;
        String url = "https://" + bucketName + "." + endpoint + "/" + s;
        // 创建PutObject请求。
        ossClient.putObject(bucketName, s, inputStream1);
        ossClient.shutdown();
        return R.success(url);
    }
}
